package partner_domains

import (
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/service/app"
)

// 添加参数
type PartnerDomainAddParams struct {
	Id        int64  `form:"id" binding:"" label:"ID"`
	PartnerId int64  `form:"partner_id"  binding:"required" label:"租户ID"`
	Domain    string `form:"domain"  binding:"required,url" label:"域名"`
	Env       int    `form:"env"  binding:"required,oneof=1 2 3" label:"环境"`
	Region    int    `form:"region"  binding:"required,oneof=1 2" label:"域"`
}

// 查询参数
type PartnerDomainQueryParams struct {
	PageSize    string `form:"page_size" binding:"gte=0,lte=100" label:"每页数量"`
	PageIndex   string `form:"page_index" binding:"gte=0,lte=99999" label:"当前页数"`
	PartnerName string `form:"partner_name"  binding:"" label:"租户名称"`
}

// join数据类型
type PartnerDomainJoin struct {
	PartnerDomains `xorm:"extends"`
	PartnerName    string
}

// 环境配置
var EnvOptions = map[int]string{
	1: "dev",
	2: "test",
	3: "prod",
}

// 域配置
var RegionOptions = map[int]string{
	1: "前端API",
	2: "管理端API",
}

// 分页获取所有数据
// @param params map 参数
// @return interface{}, error
func GetDataList(params map[string]interface{}) (map[string]interface{}, error) {
	returnData := make(map[string]interface{}, 0)

	queryParams, errBuild := model.BuildAdminQueryParam(params)
	if errBuild != nil {
		return nil, app.NewError(errBuild)
	}

	query := app.Db().Join("LEFT", "partners", "partner_domains.partner_id = partners.id").
		Desc("partner_domains.id").
		Limit(queryParams.Limit, queryParams.Offset)

	// query partner_name
	if _, ok := queryParams.Params["partner_name"]; ok && queryParams.Params["partner_name"] != "" {
		query.Where("partners.partner_name = ?", queryParams.Params["partner_name"])
	}

	data := make([]PartnerDomainJoin, 0)

	// 求总条数
	total, err := query.FindAndCount(&data)
	if err != nil {
		return nil, app.NewError(err)
	}

	// 格式化
	formatData := make([]PartnerDomainJoin, 0)
	for _, v := range data {
		v.EnvName = EnvOptions[v.Env]
		v.RegionName = RegionOptions[v.Region]
		formatData = append(formatData, v)
	}

	returnData["data"] = formatData
	returnData["total"] = total

	return returnData, nil
}

// @title AddOrUpdate
// @description 更新或者添加 一个域名, 注意域名不能重复
func (pd *PartnerDomains) AddOrUpdate(params PartnerDomainAddParams) error {

	pd.PartnerId = params.PartnerId
	pd.Domain = params.Domain
	pd.Env = params.Env
	pd.Region = params.Region

	if pd != nil && pd.Id > 0 {
		affected, errUpdate := app.Db().ID(pd.Id).Update(pd)

		if errUpdate != nil {
			return app.NewError(errUpdate)
		}

		if affected != 1 {
			return app.NewError("更新错误")
		}
	} else {
		affected, errInsert := app.Db().Insert(pd)
		if errInsert != nil {
			return app.NewError(errInsert)
		}

		if affected != 1 {
			return app.NewError("新增内容分类错误(0x001)")
		}
	}
	return nil
}

// 获取单个数据
// @param id int64 数据的id
// @return *PartnerDomains, error
func GetItemById(id int64) (*PartnerDomains, error) {
	node := new(PartnerDomains)
	has, err := app.Db().Where("id = ?", id).Get(node)

	if err != nil {
		return nil, err
	}

	if !has {
		return nil, app.NewError("对不起, 目标对象不存在")
	}

	return node, nil
}

// 获取单个数据
// @param domain string domain
// @return *PartnerDomains, error
func GetItemsByDomain(strDomain string) (*PartnerDomains, error) {
	domain := new(PartnerDomains)
	has, err := app.Db().Where("domain = ?", strDomain).Get(domain)

	if err != nil {
		return nil, err
	}

	if !has {
		return nil, app.NewError("对不起, 目标对象不存在")
	}

	return domain, nil
}

// 获取单个数据
// @title GetAllItemsFromDb
// @description 获取所有的租户
func GetAllItemsFromDb() (map[int64]*PartnerDomains, error) {
	items := make(map[int64]*PartnerDomains)
	err := app.Db().Find(&items)

	if err != nil {
		return nil, err
	}
	return items, nil
}

// @title TableName
// @description join 数据类型必须返回一个主表的　表名
func (pd PartnerDomainJoin) TableName() string {
	return "partner_domains"
}
